package cn.stylefeng.guns.modular.api;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.mapper.*;
import cn.stylefeng.guns.modular.system.model.params.SaleOrderDTO;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.*;
import cn.stylefeng.guns.modular.system.model.result.SendGoodsResult;
import cn.stylefeng.guns.modular.system.model.result.resultVO.*;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.common.*;
import cn.stylefeng.guns.sys.core.util.utility.Katrina_CJ_Utils;
import cn.stylefeng.guns.sys.core.util.utility.Order;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.util.annotation.Nullable;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

;

/** 小程序接口代码
 * @Author : xiaofei
 * @Date: 2019/6/24
 */
@RequestMapping("/api")
@RestController
public class ApiController extends BaseController {



    private static  final Joiner JOINER =Joiner.on("/").skipNulls();
    private static  final Splitter SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();

    @Autowired
    private ProductOrderService productOrderService;
    @Autowired
    private PriceService priceService;
    @Autowired
    private ClassificationService classificationService;
    @Autowired
    private  DealerLevelService dealerLevelService;
    @Autowired
    private  ProductOrderMapper productOrderMapper;
    @Autowired
    private  AfterSaleService afterSaleService;
    @Autowired
    private  ReturnService returnService;
    @Autowired
    private  AddressService addressService;
    @Autowired
    private  TroubleTypeService troubleTypeService;
    @Autowired
    private  TroubleListService troubleListService;
    @Autowired
    private UserService userService;
    @Autowired
    private SalesOrderService salesOrderService;
    @Autowired
    private InventorySalesService inventorySalesService;
    @Autowired
    private  DispatchOrderService dispatchOrderService;
    @Autowired
    private  InventoryOrderService inventoryOrderService;
    @Autowired
    private DispatchOrderMapper dispatchOrderMapper;
    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    private  PurchaseOrdersService purchaseOrdersService;
    @Autowired
    private ShopCartService shopCartService;
    @Autowired
    private SendGoodsService sendGoodsService;
    @Autowired
    private  DeptService deptService;
    @Autowired
    private  UnitService unitService;
    @Autowired
    private  IndentOrderService indentOrderService;
    @Autowired
    private IndentOrderMapper indentOrderMapper;
    @Autowired
    private SpecialProductOrderService specialProductOrderService;
    @Autowired
    private ShiWarehouseService shiWarehouseService;
    @Autowired
    private SalesOrderMapper salesOrderMapper;
    @Autowired
    private InventoryOrderMapper inventoryOrderMapper;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;
    @Autowired
    private AfterSaleMapper afterSaleMapper;
    @Resource
    private SendGoodsMapper sendGoodsMapper;
    @Autowired
    private ColorService colorService;
    @Autowired
    private PackageSizeService packageSizeService;


    /*--------------------------------------订货单接口-----------------------------------*/


    /*------------------common通·用数据-------------------------------*/
    public  List<ClassficationDTO> getValue(List<Classification> classifications){

        List<ClassficationDTO> classficationDTOS = new ArrayList<>();
        classifications.forEach((s) ->{
            ClassficationDTO classficationDTO = new ClassficationDTO();
            BeanUtils.copyProperties(s,classficationDTO);
            classficationDTO.setIsCheck(false);
            classficationDTOS.add(classficationDTO);
        });
        return  classficationDTOS;

    }

    /**
     * 获取产品分类
     * @return
     */
    @RequestMapping("/getCatgory")
    public  ResponseData getCatoryOne(Long classificationId){

        if (ToolUtil.isEmpty(classificationId)) {
            List<Classification> classificationOneList = classificationService.getBaseMapper().selectList(
                    new QueryWrapper<Classification>().eq("pid", 0)
            );
            return  ResponseData.success(200,"查询成功",getValue(classificationOneList));

        }else {
            List<Classification> classifications = classificationService.getBaseMapper().selectList(
                    new QueryWrapper<Classification>().eq("pid",classificationId)
            );
            return  ResponseData.success(200,"查询成功",getValue(classifications));
        }

    }

    /**
     * 获取产品品号信息
     * @param classificationId
     * @return
     */
    @RequestMapping("/getProductOrder")
    public ResponseData getProductOrder(Integer type,Long classificationId,Long userId){

        if (userService.getById(userId) == null){
            return ResponseData.error("暂无此用户!");
        }else {
            if (ToolUtil.isNotEmpty(classificationId)) {
                List<Classification> classifications = classificationService.getBaseMapper().selectList(
                        new QueryWrapper<Classification>().eq("pid", classificationId)
                );
                if (ToolUtil.isNotEmpty(classifications)) {
                    List<ProductOrderThreeDTO> productOrderThreeDTOS = new ArrayList<>();
                    for (Classification classification : classifications) {

                        ProductOrderThreeDTO productOrderThreeDTO = new ProductOrderThreeDTO();
                        ProductOrder productOrder = productOrderService.getOne(new QueryWrapper<ProductOrder>()
                                .eq("kind_id", classification.getId()));
                        if (ToolUtil.isNotEmpty(productOrder)) {
                            productOrderThreeDTO.setProductId(productOrder.getId());
                            productOrderThreeDTO.setProductName(productOrder.getProductOrderName());
                            productOrderThreeDTO.setPic(SystemConstant.TENCENT_URL.concat(productOrder.getPicPath().split(",")[0]));
                            productOrderThreeDTO.setRemark(productOrder.getRemark());
                            //获取经销商对应的价格
                            Long deptId = userService.getById(userId).getDeptId();
                            if (deptId != null) {
                                DealerLevel dealerLevel = (dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                                        .eq("sys_user_id", deptId)));
                                if (ToolUtil.isNotEmpty(dealerLevel))  {
                                    Price price = priceService.getOne(new QueryWrapper<Price>()
                                            .eq("product_order_id", productOrder.getKindId())
                                            .eq("level_id", dealerLevel.getLevelId()));

                                    if (type == 1) {
                                        if (ToolUtil.isNotEmpty(price)) {
                                            productOrderThreeDTO.setProductPrice(price.getProductPrice());
                                        }
                                    } else {
                                        productOrderThreeDTO.setProductPrice(productOrder.getMinSellingPrice());
                                    }
                                } else {
                                    return ResponseData.error(206, "当前经销商部门等级为空！");
                                }
                            } else {
                                return ResponseData.error(203, "当前登录者部门为空!");
                            }

                            productOrderThreeDTOS.add(productOrderThreeDTO);
                        }
                    }
                    return ResponseData.success(200, "查询成功", productOrderThreeDTOS);
                } else {
                    return ResponseData.error(202, "当前分类无数据");
                }
            } else {
                return ResponseData.error(201, "接收数据为空");
            }
        }
    }
    /**
     * 获取产品的详情信息
     * @param productOrderId
     * @return
     */
    @RequestMapping("/getProductDetail")
    public ResponseData getProductDetail(Long productOrderId){

        List<ProductOrderDTO> productOrderDTOS = productOrderMapper.productList(productOrderId);
        productOrderDTOS.stream().map(s -> SystemConstant.TENCENT_URL + s.getReportCertificate()).collect(Collectors.toList());
        productOrderDTOS.forEach((s) -> {
            List<String> pic = Arrays.asList(s.getPicPath().split(","));
            s.setPicPathList(pic.stream().map(p -> SystemConstant.TENCENT_URL + p).collect(Collectors.toList()));

            List<UnitDTO> units = new ArrayList<>();
            UnitDTO unitDTO = new UnitDTO(s.getUnitMin(),s.getUnitMinName(),true);
            units.add(unitDTO);
            UnitDTO unitDTOMax = new UnitDTO(s.getUnitMax(),s.getUnitMaxName(),false);
            units.add(unitDTOMax);
            s.setUnits(units);
        });
        return  ResponseData.success(200,"查询成功",productOrderDTOS);
    }


    /**
     * 添加购物车
     * @param
     * @return
     */
    @RequestMapping("/addCart")
    public  ResponseData addShopCart(Long productId, Integer unitId,Long userId){

        ShopCart shopCartNew =  shopCartService.getOne(new QueryWrapper<ShopCart>()
                .lambda().eq(ShopCart::getProductId,productId));

        if (ToolUtil.isNotEmpty(shopCartNew)){
            shopCartNew.setAmout(shopCartNew.getAmout() + 1);
            shopCartService.getBaseMapper().updateById(shopCartNew);
            return  ResponseData.success(200,"添加购物车成功",shopCartNew);
        }else {

            ShopCart shopCart = new ShopCart();
            shopCart.setProductId(productId);
            shopCart.setUnitId(unitId);
            shopCart.setCreateTime(new Date());
            shopCart.setUserId(userId);
            shopCart.setAmout((long) 1);
            shopCartService.getBaseMapper().insert(shopCart);
            return  ResponseData.success(200,"添加购物车成功",shopCart);
        }
    }
    /**
     * 查询购物车
     * @return
     */
    @RequestMapping("/listShopCart")
    public ResponseData listShopCart(Integer type,Long userId){

        List<ShopCart> shopCarts =shopCartService.getBaseMapper().selectList(new
                QueryWrapper<ShopCart>().lambda().eq(ShopCart::getUserId,userId).orderByDesc(ShopCart::getCreateTime));
        List<ShopCartDTO> shopCartDTOS = new ArrayList<>();
        shopCarts.forEach(( s) ->{

            ShopCartDTO shopCartDTO =  new ShopCartDTO();

            BeanUtils.copyProperties(s,shopCartDTO);
            //添加产品详细信息
            ProductOrder productOrder = productOrderService.getById(s.getProductId());
            if (ToolUtil.isNotEmpty(productOrder)) {
                Classification three = classificationService.getById(productOrder.getKindId());
                shopCartDTO.setProductOrderName(three.getName());
                Classification two = classificationService.getById(three.getPid());
                shopCartDTO.setProductModelName(two.getName());
                Classification one = classificationService.getById(two.getPid());
                shopCartDTO.setProductName(one.getName());

                //获取产品价格
                if (type == 1 ) {
                    Price price = priceService.getOne(new QueryWrapper<Price>()
                            .lambda().eq(Price::getProductOrderId, productOrder.getKindId())
                            .eq(Price::getLevelId, dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                                    .lambda().eq(DealerLevel::getSysUserId, userService.getById(userId).getDeptId())).getLevelId()));
                    shopCartDTO.setPrice(price.getProductPrice());
                }else {
                    shopCartDTO.setPrice(productOrder.getMinSellingPrice());
                }
                //获取产品图片
                shopCartDTO.setProductPic(SystemConstant.TENCENT_URL.concat(productOrder.getPicPath().split(",")[0]));

                //获取单位名称
                if (ToolUtil.isNotEmpty(unitService.getById(s.getUnitId()))) {
                    shopCartDTO.setUnitName(unitService.getById(s.getUnitId()).getUnitName());
                }
                shopCartDTO.setAddtime(s.getCreateTime());
                shopCartDTO.setChecked(false);
                shopCartDTOS.add(shopCartDTO);
            }
        });

        Map<String,Object> map = new HashMap<>();
        if (deptService.getById(userService.getById(userId)).getSimpleName().contains("部门3")){
            map.put("address",dealerLevelService.getOne(new QueryWrapper<DealerLevel>().eq("sysUserId",userService.getById(userId).getDeptId())).getAddress());
        }else {
            map.put("address","暂无地址");
        }

        map.put("shopCartDTOS",shopCartDTOS);
        return  ResponseData.success(200,"查询成功",shopCartDTOS);
    }


    /**
     * 插入到订货单中
     * @param
     * @return
     */
    @RequestMapping("/submitIndet")
    public ResponseData submitIndent(String indentDto,Long userId){
        //1.先插入到采购单中 ，然后添加到订货单
        List<IndentOrderSubmitDto> indentOrderSubmitDtos = JSON.parseArray(indentDto, IndentOrderSubmitDto.class);
        StringBuilder ids = new StringBuilder();
        indentOrderSubmitDtos.forEach((s) -> {
            //1.插入到 采购单中
            PurchaseOrders purchaseOrders = new PurchaseOrders();
            BeanUtils.copyProperties(s,purchaseOrders);

            //查询当前产品品号的详情信息
            BigDecimal totalPrice = null;
            ProductOrder productOrder = productOrderService.getById(s.getProductId());
              if (s.getUnitId().equals(productOrder.getUnit())){
                  totalPrice = s.getPrice().multiply(new BigDecimal(s.getOrderNumbers())).setScale(2,BigDecimal.ROUND_HALF_UP);
              }else {
                 totalPrice = s.getPrice().multiply(s.getPrice()).multiply(new BigDecimal(productOrder.getConversionRatio())).setScale(2,BigDecimal.ROUND_HALF_UP);
             }
            purchaseOrders.setOrderAmount(totalPrice);
            purchaseOrders.setNotSendPrice(totalPrice);
            purchaseOrders.setNotSend(new BigDecimal(s.getOrderNumbers()));
            purchaseOrders.setHavaSend(new BigDecimal(0));
            purchaseOrders.setHavaSendPrice(new BigDecimal(0));
            purchaseOrders.setStatus(StatusCode.DOING.getVal());
            purchaseOrders.setDispatchNum((long)1);

            purchaseOrdersService.save(purchaseOrders);

            //找出刚插入的采购单
            PurchaseOrders purchaseOrdersLast= purchaseOrdersService.getOne(new QueryWrapper<PurchaseOrders>()
                    .lambda().orderByDesc(PurchaseOrders::getPurchaseId).last("limit 1"));
            ids.append(purchaseOrdersLast.getPurchaseId()+ ",");

            //删除购物车中选中的商品
            shopCartService.getBaseMapper().delete(new QueryWrapper<ShopCart>()
                    .lambda().eq(ShopCart::getUserId,userId)
                    .eq(ShopCart::getProductId,s.getProductId()));
        });

        //插入订货单中

        IndentOrder indentOrder = new IndentOrder();
        indentOrder.setDealer(userId);
        indentOrder.setTime(new Date());
        indentOrder.setCheckCode(StatusCode.PENDING.getVal());
        indentOrder.setPurchaseId(ids.toString());

        //设置订货单编号
        IndentOrder  indentOrderLast = indentOrderService.getOne(new QueryWrapper<IndentOrder>()
                .lambda().orderByDesc(IndentOrder::getId).last("limit 1"));
        if (ToolUtil.isNotEmpty(indentOrderLast)){
            indentOrder.setIndentOrderNum(Katrina_CJ_Utils.createOrderSerial(Order.NM_,indentOrderLast.getId()));
        }else {
            indentOrder.setIndentOrderNum(Katrina_CJ_Utils.createOrderSerial(Order.NM_,(long)1));
        }

        indentOrder.setIndentStatus(StatusCode.DOING.getVal());

        identityService.setAuthenticatedUserId(userId +"");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.pc_indent_order);
        indentOrder.setProcessInstanceId(processInstance.getId());
        indentOrderService.save(indentOrder);

        //开启流程
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.setAssignee(task.getId(),userId +"");
        taskService.complete(task.getId());
        //接支付接口
        return  ResponseData.success(200,"购买成功",indentOrder);
    }


    /**
     * 申请发货
     * @param indentOrderId
     * @return
     */
    @RequestMapping("/applicationDispath")
    public  ResponseData applicationDispathList(Long indentOrderId, PageDTO pageDTO,Long userId){

        //过滤未发货数量为零的单据
        IndentOrder indentOrder = indentOrderService.getById(indentOrderId);
        Page page = new Page();
        BeanUtils.copyProperties(pageDTO,page);
        Page<PurchaseOrderDTO> purchaseOrderDTOS = purchaseOrdersMapper.getDispatchList(page,Arrays.asList(indentOrder.getPurchaseId().split(",")).stream().map(s -> Long.parseLong(s)).collect(Collectors.toList()));
        List<PurchaseOrderDTO> purchaseOrderDTOSUse = purchaseOrderDTOS.getRecords().stream().filter(s -> s.getNotSend() != new BigDecimal(0)).collect(Collectors.toList());
        purchaseOrderDTOSUse.forEach((s) -> {
            s.setChecked(false);
            s.setPic(SystemConstant.TENCENT_URL.concat(s.getPic()));
            s.setPrice(priceService.getOne(new QueryWrapper<Price>().lambda()
                    .eq(Price::getProductOrderId,
                            productOrderService.getById(s.getProductId()).getKindId())
                    .eq(Price::getLevelId,
                            dealerLevelService.getOne(new QueryWrapper<DealerLevel>().lambda().eq(DealerLevel::getSysUserId,userService.getById(userId).getDeptId())).getLevelId())).getProductPrice());
        });
        purchaseOrderDTOS.setRecords(purchaseOrderDTOSUse);
        LayuiPageFactory.createPageInfo(purchaseOrderDTOS);
        Map<String,Object> map = new HashMap<>();
        map.put("page",purchaseOrderDTOS);
        map.put("indentId",indentOrderId);
        return  ResponseData.success(200,"查询成功",map);
    }

    /**
     * 提交发货申请
     * @param
     * @return
     */
    @RequestMapping("/applicationDispathCommit")
    public ResponseData applicationDispathCommit(DispatchCommitDTO dispatchCommitDTO){

        List<ApplicationDispathDto> applicationDispathDtos = JSON.parseArray(dispatchCommitDTO.getDispatchCommit(),ApplicationDispathDto.class);
        StringBuilder ids = new StringBuilder();
        applicationDispathDtos.forEach(s -> {

            //1.更新每个库存中的数据
            PurchaseOrders purchaseOrders = purchaseOrdersService.getById(s.getPurchaseId());
            BeanUtils.copyProperties(s,purchaseOrders);
            BigDecimal price = null;
            if (s.getUnitId().equals(productOrderService.getById(purchaseOrders.getProductId()).getUnit())){
                price = new BigDecimal(s.getDispatchNum()).multiply(purchaseOrders.getPrice()).setScale(2,BigDecimal.ROUND_HALF_UP);
            }else {
                price = new BigDecimal(s.getDispatchNum()).multiply(purchaseOrders.getPrice()).multiply(new BigDecimal(productOrderService.getById(purchaseOrders.getProductId()).getConversionRatio()).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
            purchaseOrders.setHavaSend(price);
            purchaseOrders.setNotSend(purchaseOrders.getOrderAmount().subtract(price).setScale(2,BigDecimal.ROUND_HALF_UP));
            purchaseOrdersService.getBaseMapper().updateById(purchaseOrders);

            ids.append(s.getPurchaseId() + ",");
        });

        //生成申请发货单`
        DispatchOrder dispatchOrder = new DispatchOrder();
        //找到最后一个申请发货单号
        DispatchOrder dispatchOrderLast = dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
                .lambda().orderByDesc(DispatchOrder::getId).last("limit 1"));
        if (ToolUtil.isNotEmpty(dispatchOrderLast)){
            dispatchOrder.setOrderNum(Katrina_CJ_Utils.createOrderSerial(Order.SQ_,dispatchOrderLast.getId()));
        }else {
            dispatchOrder.setOrderNum(Katrina_CJ_Utils.createOrderSerial(Order.SQ_,(long)1));
        }
        dispatchOrder.setDealerId(dispatchCommitDTO.getUserId());
        dispatchOrder.setCheckCode(StatusCode.PENDING.getVal());
        dispatchOrder.setPurchaseOrdersId(ids.toString());
        dispatchOrder.setCreateTime(new Date());
        dispatchOrder.setIndentId(dispatchCommitDTO.getIndentId());
        dispatchOrder.setDispatchCode(StatusCode.PENDING.getVal());


        identityService.setAuthenticatedUserId(dispatchCommitDTO.getUserId() +"");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.sendOrder);
        dispatchOrder.setProcessInstanceId(processInstance.getId());
        dispatchOrderService.save(dispatchOrder);

        //开启流程
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.setAssignee(task.getId(),dispatchCommitDTO.getUserId() +"");
        taskService.complete(task.getId());
        return  ResponseData.success(200,"添加订单成功",dispatchOrder);
    }


    /*------------------查询单据--------------------------------*/

    /**
     * 查询订货单单据
     * @param code
     * @return
     */
    @RequestMapping("/selectIndentOrderList")
    public  ResponseData selectIndentOrderList(Integer code,Long userId,PageDTO pageDTO){

        Page page = new Page();
        BeanUtils.copyProperties(pageDTO,page);
        IPage IndentPage  = indentOrderMapper.selectIndentList(page,userId,code);
        LayuiPageInfo indentList = LayuiPageFactory.createPageInfo(IndentPage);
        return  ResponseData.success(200,"查询成功",indentList);
    }
    //查看订单详情
    @RequestMapping("/indentOrderDetail")
    public ResponseData indentOrderDetail(/*Map<String,Object> map*/ Long indentId,PageDTO pageDTO,Long userId){

       IndentOrder indentOrder = indentOrderService.getById(indentId);
       if (ToolUtil.isNotEmpty(indentOrder)){
           Page page = new Page();
           Katrina_CJ_Utils.pageSet(page,pageDTO.getCurrent(),pageDTO.getSize());
           Page indentDetail = purchaseOrdersMapper.getPurchaseByDealer(page,Katrina_CJ_Utils.getIds(indentOrder.getPurchaseId()),userId);
           return  ResponseData.success(200,"查询数据成功",LayuiPageFactory.createPageInfo(indentDetail));
       }else {
           return  ResponseData.error("无此订单！");
       }
    }

    /**
     * 取消订单
     * @param indentId
     * @return
     */
    @RequestMapping("/cancelIndent")
    public ResponseData cancelIndent(Long indentId){
      return null;
    }

    /**
     * 查询申请发货单
     * @param applicationIndenDto
     * @return
     */
      @RequestMapping("/selectPurchaseOrderList")
      public  ResponseData selectPurchaseOrderList( ApplicationIndenDto applicationIndenDto){

        Page page = new Page();
        Katrina_CJ_Utils.pageSet(page,applicationIndenDto.getCurrent(),applicationIndenDto.getSize());
        Page<ApplicationDispatchVO> ApplicationDispath = dispatchOrderMapper.selectPurchaseList(page,applicationIndenDto.getUserId(),applicationIndenDto.getCode(),applicationIndenDto.getIndentOrderNum());
        LayuiPageInfo pageInfo = LayuiPageFactory.createPageInfo(ApplicationDispath);
        return ResponseData.success(200,"查询成功",pageInfo);
    }



    //判断销售订单是否为特价 状态
    @RequestMapping("/submitSaleOrder")
    public ResponseData submitSaleOrder(String saleOrderSubmit,Long userId){

      List<IndentOrderSubmitDto> saleOrderSubmitDTOS = JSON.parseArray(saleOrderSubmit,IndentOrderSubmitDto.class);
      List<IndentOrderSubmitDto> specialPrice = saleOrderSubmitDTOS.stream()
             .filter(s -> s.getPrice() != null)
              .collect(Collectors.toList())
              .stream()
              .filter(s -> specialProductOrderService.getOne(new QueryWrapper<SpecialProductOrder>()
              .lambda().eq(SpecialProductOrder::getUserId,userId)
              .eq(SpecialProductOrder::getProductPrice,s.getPrice())
              .eq(SpecialProductOrder::getProductOrderId,s.getProductId())) ==null )
              .collect(Collectors.toList())
              .stream()
              .filter(s -> s.getPrice().compareTo(productOrderService.getById(s.getProductId()).getMinSellingPrice()) == -1)
              .collect(Collectors.toList());
      Map<String,Object> map  = new HashMap<>();
      map.put("number",specialPrice.size());
      map.put("saleOrderList",specialPrice);
      if (ToolUtil.isNotEmpty(specialPrice)){
          return ResponseData.success(201,"需要特价申请",map);
      }else {
          return ResponseData.success(200,"不需要特价审核",saleOrderSubmitDTOS);
      }
    }


    //提交申请and提交订货单
    @RequestMapping("/specialSaleOrderSubmit")
    public  ResponseData specialSaleOrderSubmit(SaleOrderSubmitDTO saleOrderSubmitDTO){
          List<IndentOrderSubmitDto> specialPrice = JSON.parseArray(saleOrderSubmitDTO.getSpecialSaleOrder(),IndentOrderSubmitDto.class);
          //将数据插入到采购单中
         StringBuilder ids = new StringBuilder();
         specialPrice.forEach((s) -> {
             PurchaseOrders  purchaseOrders = new PurchaseOrders();
             BeanUtils.copyProperties(s,purchaseOrders);
             purchaseOrders.setOrderAmount(new BigDecimal(s.getOrderNumbers()).multiply(s.getPrice()));
             purchaseOrdersService.getBaseMapper().insert(purchaseOrders);
             //找到刚插入数据的id
             PurchaseOrders purchaseOrdersLast =  purchaseOrdersService.getOne(new QueryWrapper<PurchaseOrders>()
             .lambda().orderByDesc(PurchaseOrders::getPurchaseId).last("limit 1"));
             ids.append(purchaseOrdersLast.getPurchaseId() + ",");
         });

         //插入到特价审核单
         SalesOrder salesOrder = new SalesOrder();
         SalesOrder salesOrderLast =  salesOrderService.getOne(new QueryWrapper<SalesOrder>()
         .lambda().orderByDesc(SalesOrder::getId).last("limit 1"));
         if (ToolUtil.isNotEmpty(salesOrderLast)){
             salesOrder.setSerialNumOrder(Katrina_CJ_Utils.createOrderSerial(Order.TJ_,salesOrderLast.getId()));
         }else {
             salesOrder.setSerialNumOrder(Katrina_CJ_Utils.createOrderSerial(Order.TJ_,(long)1));
         }
         salesOrder.setPurchaseOrderId(ids.toString());
         salesOrder.setSalesUserId(saleOrderSubmitDTO.getUserId());
         salesOrder.setCreateTime(new Date());
         if (saleOrderSubmitDTO.getType() == 1) {
             identityService.setAuthenticatedUserId(saleOrderSubmitDTO.getUserId() + "");
             ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.SpecialSaleOrder);
             salesOrder.setProcessInstanceId(processInstance.getId());
             salesOrder.setSpecialPriceStaus(StatusCode.PENDING.getVal());
         }else {
             if (saleOrderSubmitDTO.getType() == 2) {

                 if (saleOrderSubmitDTO.getSalsType() == 1){
                     StringBuilder serialNum = new StringBuilder();
                     //减少当前门店的库存
                     List<String> idss = Arrays.asList(saleOrderSubmitDTO.getInventoryIds().split(","));
                     for(String str:idss){
                         InventoryOrder inventoryOrder = inventoryOrderService.getById(Long.parseLong(str));
                         serialNum.append(inventoryOrder.getSerialNum() + "|");
                         inventoryOrderService.getBaseMapper().deleteById(Long.parseLong(str));
                     }
                     salesOrder.setSerialNum(serialNum.toString());
                     salesOrder.setSalsType(1);
                 }else {
                     salesOrder.setStatus(StatusCode.PENDING.getVal());
                     salesOrder.setSalsType(2);
                     identityService.setAuthenticatedUserId(saleOrderSubmitDTO.getUserId() +"");
                     ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.SaleOrder);
                     salesOrder.setProcessInstanceId(processInstance.getId());
                 }
             }
             BeanUtils.copyProperties(saleOrderSubmitDTO,salesOrder);
         }
         salesOrder.setSalesDept(deptService.getById(userService.getById(saleOrderSubmitDTO.getUserId())).getSimpleName());
         salesOrderService.getBaseMapper().insert(salesOrder);

         SalesOrder salesOrderNew = salesOrderService.getOne(new QueryWrapper<SalesOrder>()
         .lambda()
         .orderByDesc(SalesOrder::getId)
         .last("limit 1"));
         if (saleOrderSubmitDTO.getType() == 1){
              //找到刚插入的申请特价单
             Task task =  taskService.createTaskQuery().processInstanceId(salesOrderNew.getProcessInstanceId()).singleResult();
             taskService.setAssignee(task.getId(),saleOrderSubmitDTO.getUserId() +"");
             taskService.complete(task.getId());
         }else {
             if (saleOrderSubmitDTO.getSalsType() == 2){
                 Task task = taskService.createTaskQuery().processInstanceId(salesOrderNew.getProcessInstanceId()).singleResult();
                 taskService.setAssignee(task.getId(),saleOrderSubmitDTO.getUserId() +"");
                 taskService.complete(task.getId());
             }
         }
         return  ResponseData.success(200,"添加订单成功",salesOrder);
    }


    //查询特价审核单
    @RequestMapping("/selectSpecialList")
    public ResponseData selectSpecialList(Long current,Long size,Long userId,Integer code){

         Page page = new Page();
         Katrina_CJ_Utils.pageSet(page,current,size);
         Page pageUse = salesOrderMapper.specialOrderList(page,userId,code);
         return  ResponseData.success(200,"查询成功",LayuiPageFactory.createPageInfo(pageUse));
    }


    /**
     * 查询销售单列表 salsType = 0 表示是 门店销售订单 ，salsType = 1 普通销售订单
     * @param saleOrderDTO
     * @return
     */
    @RequestMapping("/selectSalsOrderList")
    public  ResponseData selectSalsOrderList(SaleOrderDTO saleOrderDTO){

        Page page = new Page();
        Katrina_CJ_Utils.pageSet(page,saleOrderDTO.getCurrent(),saleOrderDTO.getSize());
        Page salesOrderList = null;
        switch (saleOrderDTO.getSalsType()){
            case 1:
                salesOrderList = salesOrderMapper.selectSaleOrderList(page,saleOrderDTO.getUserId(),saleOrderDTO.getSalsType());
                break;
            case 2:
                salesOrderList = salesOrderMapper.selectSaleList(page,saleOrderDTO.getUserId(),saleOrderDTO.getSalsType(),saleOrderDTO.getCode());
        }

      return  ResponseData.success(200,"查询成功",LayuiPageFactory.createPageInfo(salesOrderList));

    }


    /**
     * 查询门店库存
     * @param userId
     * @param current
     * @param size
     * @return
     */
    @RequestMapping("/inventoryOrderList")
    public  ResponseData inventoryOrderList(Long userId,Long current,Long size){
        Page page  =  new Page();
        Katrina_CJ_Utils.pageSet(page,current,size);
        Long warhouseId = shiWarehouseService.getOne(new QueryWrapper<ShiWarehouse>()
                .lambda().eq(ShiWarehouse::getPid,userService.getById(userId).getDeptId())).getId();
        Page<InventoryVO> inventoryVOList = inventoryOrderMapper.getInventoryList(page,warhouseId);
        inventoryVOList.getRecords().stream().forEach(s -> s.setChecked(false));
        return  ResponseData.success(200,"查询库存成功",LayuiPageFactory.createPageInfo(inventoryVOList));
    }
    //查询销售订单
    /*----------------------------售后维修单---------------------------------------*/

    /**
     * 维修单
     * @param afterSale
     * @return
     */
    @RequestMapping("/saleAfter")
    public  ResponseData saleAfterOrder(String afterSale){

        AfterSaleVO afterSaleVO = JSON.parseObject(afterSale,AfterSaleVO.class);
        AfterSale afterSaleInsert = new AfterSale();
        //1.前台数据插入到数据库中
        BeanUtils.copyProperties(afterSaleVO,afterSaleInsert);
        afterSaleInsert.setStatus(StatusCode.PENDING.getVal());

        //设置售后单号
        //1.查找出当前最新的一个售后单
        AfterSale afterSaleLast = afterSaleService.getOne(new QueryWrapper<AfterSale>()
                .lambda().orderByDesc(AfterSale::getId).last("limit 1"));
        afterSaleInsert.setAfterSaleOrder(Katrina_CJ_Utils.createOrderSerial(Order.SH_,afterSaleLast.getId()));
        afterSaleInsert.setSalesUserId(ShiroKit.getUserNotNull().getId());
        afterSaleService.save(afterSaleInsert);
        return  ResponseData.success();

    }

    /**
     * 退货单
     * @param returns
     * @return
     */
    @RequestMapping("/returnOrder")
    public ResponseData returnOrder(String returns){
        ReturnVO returnVO = JSON.parseObject(returns,ReturnVO.class);
        Return returnGoods = new Return();
        //1前台数据插入到数据库中
        BeanUtils.copyProperties(returnVO,returnGoods);
        returnGoods.setStatus(StatusCode.PENDING.getVal());
        returnService.save(returnGoods);
        return  ResponseData.success();
    }

    /*-----------------------消费者接口--------------------------------------*/

    /**
     * 用户注册
     * @param userVO
     * @return
     */
    @RequestMapping("/registerUser")
    public  ResponseData register(UserVO userVO){
        User userInset = new User();
        BeanUtils.copyProperties(userVO,userInset);
        String salt = ShiroKit.getRandomSalt(6);
        userInset.setSalt(salt);
        userInset.setPassword(ShiroKit.md5(userVO.getPassword(),salt));

        //查询序列号
        List<SalesOrder> salesOrder = salesOrderService.getBaseMapper().selectList(new QueryWrapper<SalesOrder>()
                .lambda().eq(SalesOrder::getSalesPhone,userVO.getPhone()));
        Boolean b = false;
       for (SalesOrder salesOrderUse:salesOrder) {


           if (ToolUtil.isNotEmpty(salesOrderUse.getSerialNum())) {
               if (salesOrderUse.getSerialNum().contains(userVO.getSerials())) {
                   b = true;
                   break;
               }
           } else {

               SendGoods sendGoods = sendGoodsService.getOne(new QueryWrapper<SendGoods>()
                       .lambda().eq(SendGoods::getSaleId, salesOrderUse.getId())
                       .eq(SendGoods::getIsComplete, StatusCode.DONE.getVal()));
               List<Long> ids = Arrays.asList(sendGoods.getInventoryOrderId().split(",")).stream().map(s -> Long.parseLong(s)).collect(Collectors.toList());


               for (Long id : ids) {
                   InventoryOrder inventoryOrder = inventoryOrderService.getById(id);
                   if (inventoryOrder.getSerialNum().contains(userVO.getSerials())) {
                       b = true;
                       break;
                   }
               }
           }
       }
        if (b == true) {
            userInset.setDeptId(deptService.getOne(new QueryWrapper<Dept>()
                    .lambda().eq(Dept::getSimpleName, "温州经销商")).getDeptId());
            userService.save(userInset);
            return ResponseData.success(200, "注册成功", userInset);
        } else {
            return ErrorResponseData.error("序列号不存在！");
        }

    }


    /**
     * 获取当前消费者的订单
     * @param current
     * @param size
     * @param phone
     * @return
     */
    @RequestMapping("/getCustomSaleList")
    public  ResponseData getCustomSaleList(Long current,Long size,String phone){
        Page page = new Page();
        Katrina_CJ_Utils.pageSet(page,current,size);
        Page<CustomSalesList> pageUse = salesOrderMapper.selectCustomList(page,phone);
        return   ResponseData.success(200,"查询成功",LayuiPageFactory.createPageInfo(pageUse));
    }


    /**
     * 获取当前订单的商品信息
     * @param id
     * @return
     */
    @RequestMapping("/getCustomeSalesDetail")
    public ResponseData getCustomeSalesDetail(Long id,Long current,Long size){
        Page page  =new Page();
        Katrina_CJ_Utils.pageSet(page,current,size);
        //获取当前订单的详细信息
        SalesOrder salesOrder = salesOrderService.getById(id);
        Page pageUse = purchaseOrdersMapper.getCustomDetail(page,Katrina_CJ_Utils.getIds(salesOrder.getPurchaseOrderId()));
        List<CustomSaleDetailDTO> customSaleDetailDTOS = pageUse.getRecords();
        customSaleDetailDTOS.stream().forEach(s -> s.setPic(SystemConstant.TENCENT_URL+s.getPic().split(",")[0]));
        return  ResponseData.success(200,"查询订单成功",LayuiPageFactory.createPageInfo(pageUse));
    }

    /**
     * 创建售后单
     * @param afterSaleOrderDTO
     * @return
     */
    @RequestMapping("/insetAfterSale")
   public ResponseData insetAfterSale(AfterSaleOrderDTO afterSaleOrderDTO){

        //创建售后订单
        AfterSale afterSale = new AfterSale();
        BeanUtils.copyProperties(afterSaleOrderDTO,afterSale);
        afterSale.setSalesUserId(afterSaleOrderDTO.getUserId());
        afterSale.setStatus(StatusCode.PENDING.getVal());
        //找出最近的一条售后订单
        AfterSale afterSaleLast = afterSaleService.getOne(new QueryWrapper<AfterSale>()
        .lambda().orderByDesc(AfterSale::getId).last("limit 1"));
        afterSale.setAfterSaleOrder(afterSaleLast == null ? Katrina_CJ_Utils.createOrderSerial(Order.SH_,(long)1):Katrina_CJ_Utils.createOrderSerial(Order.SH_,afterSaleLast.getId()));
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.charAfterSale);
        afterSale.setProcessInstanceId(processInstance.getId());
        identityService.setAuthenticatedUserId(afterSaleOrderDTO.getUserId() + "");
        afterSaleService.save(afterSale);

        //开启流程
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.setAssignee(task.getId(),afterSaleOrderDTO.getUserId().toString());
        taskService.complete(task.getId());
        return  ResponseData.success(200,"创建售后单成功",afterSale);
   }

    /**
     * 上传文件接口
     * @param file
     * @return
     */
    @RequestMapping("/uploadFile")
    public ResponseEntity<?> uploadFile(MultipartFile file){

        ResponseMsg msg = new ResponseMsg();
        msg = UploadFileUtils.uploadFile(file);
        if (msg.getStatus() == 10001){
            UploadResult result = (UploadResult) msg.getResult();
            msg.setResponseSuccess("上传成功！",SystemConstant.TENCENT_URL+result.getPath());
        }else {
            msg.setResponseError(SysErrorCode.UPLOAD_ERROR);
        }
        return  new ResponseEntity<>(msg,HttpStatus.OK);
    }


    /**
     * 获取问题类型
     * @return
     */
    @RequestMapping("/getTroubleType")
    public ResponseData getTroubleType(){

        List<TroubleType> troubleTypes = troubleTypeService.list();
        return  ResponseData.success(200,"查询成功",troubleTypes);
    }

    /*
    获取问题类型集
     */
    @RequestMapping("/getTroubleList")
    public ResponseData getTroubleList(Integer type){

        QueryWrapper<TroubleList> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TroubleList::getTroubleTypeId,type);
        List<TroubleList> troubleLists = troubleListService.list(queryWrapper);
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        troubleLists.stream().forEach(s ->{
            map.put("id",s.getId());
            map.put("troubleDescription",s.getTroubleDescription());
            list.add(map);
        });
        return  ResponseData.success(200,"查询成功",list);
    }

    /**
     * 售后维修单列表
     * @param userId
     * @param code
     * @return
     */
    @RequestMapping("/selectAfterSale")
    public ResponseData selectAfterSale(Long userId,Integer code,PageDTO pageDTO){
        Page page = new Page();
        Katrina_CJ_Utils.pageSet(page,pageDTO.getCurrent(),pageDTO.getSize());
        Page pageUse = afterSaleMapper.lists(page,userId,code);
      return  ResponseData.success(200,"查询成功",LayuiPageFactory.createPageInfo(pageUse));
    }

    /**
     * 获取售后单详情
     * @param indentId
     * @return
     */
    @RequestMapping("/afterSaleDetail")
    public ResponseData afterSaleDetail(Long indentId) {
        AfterSaleDTO afterSaleDTO = new AfterSaleDTO();
        AfterSale afterSale = afterSaleService.getById(indentId);
        BeanUtils.copyProperties(afterSale, afterSaleDTO);
        if (ToolUtil.isNotEmpty(afterSale.getProductMaintainerId())) {
            afterSaleDTO.setProductMaintainer(userService.getById(afterSale.getProductMaintainerId()).getName());
        } else if (ToolUtil.isNotEmpty(afterSale.getDealerMaintainerId())) {
            afterSaleDTO.setProductMaintainer(userService.getById(afterSale.getDealerMaintainerId()).getName());
        }
        Classification classification = classificationService.getById(afterSale.getProductTypeId());
        StringBuilder peijian = new StringBuilder();
        if (ToolUtil.isNotEmpty(classification)) {
            peijian.append(classification.getName());
            Classification classificationPid = classificationService.getById(classification.getPid());
            peijian.append(classificationPid.getName());
            if (classification.getPid() != 0) {
                Classification classificationPpid = classificationService.getById(classificationPid.getPid());
                peijian.append(classificationPpid.getName());
                afterSaleDTO.setPeijian(peijian.toString());
            } else {
                afterSaleDTO.setPeijian(peijian.toString());
            }
        }
        if (ToolUtil.isNotEmpty(afterSale.getTroublePicture())) {
           afterSaleDTO.setTroublePicture(Arrays.asList(afterSale.getTroublePicture())
           .stream()
           .map(s -> SystemConstant.TENCENT_URL.concat(s)).collect(Collectors.toList()));
        }
        if (ToolUtil.isNotEmpty(afterSale.getBeforePicture())) {
            afterSaleDTO.setBeforePicture(Arrays.asList(afterSale.getBeforePicture())
                    .stream()
                    .map(s -> SystemConstant.TENCENT_URL.concat(s)).collect(Collectors.toList()));
        }
        if (ToolUtil.isNotEmpty(afterSale.getAfterPicture())) {
            afterSaleDTO.setAfterPicture(Arrays.asList(afterSale.getAfterPicture())
                    .stream()
                    .map(s -> SystemConstant.TENCENT_URL.concat(s)).collect(Collectors.toList()));
        }
        return ResponseData.success(200,"查询成功",afterSaleDTO);
    }
    /**
     * 获取问题解决详情
     * @param id
     * @return
     */
    @RequestMapping("/getTroubleDetail")
    public ResponseData getTroubleDetail(Long id){

        TroubleList troubleList = troubleListService.getById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("troubleLsit",troubleList);
        if (ToolUtil.isNotEmpty(troubleList.getTroublePicture())) {
            List<String> pics = Arrays.asList(troubleList.getTroublePicture().split(",")).stream()
                    .map(s -> SystemConstant.TENCENT_URL.concat(s)).collect(Collectors.toList());
            map.put("pics",pics);
        }
        return ResponseData.success(200,"查询成功",map);
    }


    /**
     * 删除购物车
     * @param id
     * @return
     */
    @RequestMapping("/deleteShopCard")
    public ResponseData deleteShopCard(Long id){
        if (ToolUtil.isNotEmpty(id)) {
            shopCartService.getBaseMapper().deleteById(id);
            return ResponseData.success(200, "删除成功", id);
        }else {
            return ResponseData.error("插入参数为空");
        }
    }



    /*---------------------------------------------------------------------------------------------*/
    /**
     * 查询发货单
     * @return
     */
    @RequestMapping("/dispatchList")
    public  ResponseData selectDispatchList(){
        Page page = LayuiPageFactory.defaultPage();
        IPage iPage= dispatchOrderMapper.queryAllByDealerId(page, ShiroKit.getUserNotNull().getId());
        LayuiPageInfo dispatchList = LayuiPageFactory.createPageInfo(iPage);
        return  ResponseData.success(200,"查询成功",dispatchList);
    }

    @RequestMapping("/purchaseDetails")
    public ResponseData  selectPurchase(
            Long dispatchId){
        //1.查出当前发货单的详情信息
        DispatchOrder dispatchOrder = dispatchOrderService.getById(dispatchId);
        //2.把库存信息表里的 采购单里id集合给取出来
        List<String> idStr = Arrays.asList(dispatchOrder.getPurchaseOrdersId().split(","));
        List<Long> ids  =  idStr.stream().map((s) -> Long.parseLong(s)).collect(Collectors.toList());
        List<PurchaseDetailVO> purchaseDetailVO=purchaseOrdersMapper.selectPurchase(ids);
        return ResponseData.success(200,"查询成功",purchaseDetailVO);
    }

    /**
     * 查看发货单
     * @param pageDTO
     * @param userId
     * @return
     */
    @RequestMapping("/sendGoodList")
    public ResponseData sendGoodsList(PageDTO pageDTO,Long userId,Integer code){
        Page page = new Page();
        Katrina_CJ_Utils.pageSet(page,pageDTO.getCurrent(),pageDTO.getSize());
        Page<SendGoodsResult> pageUse = sendGoodsMapper.selectSendGoodList(page,code,userId);
        return ResponseData.success(200,"查看发货单成功",pageUse);
    }

    @Nullable
    @RequestMapping("/getProdcutDetail")
    public  ResponseData getProdcutDetail(Long prodcutOrderId) {

        if (ToolUtil.isNotEmpty(prodcutOrderId)) {
            ProductOrder productOrder = productOrderService.getById(prodcutOrderId);
            ProductOrderDetailVO productOrderDetailVO = new ProductOrderDetailVO();
            BeanUtils.copyProperties(productOrder, productOrderDetailVO);

            //1.查询产品名
            Classification classification = classificationService.getById(productOrder.getKindId());
            if (ToolUtil.isNotEmpty(classification)) {
                productOrderDetailVO.setProdcutModelName(classification.getName());
                Classification classificationTwo = classificationService.getById(classification.getPid());
                if (ToolUtil.isNotEmpty(classificationTwo)) {
                    productOrderDetailVO.setProdcutModelName(classificationTwo.getName());
                    Classification classificationThree = classificationService.getById(classificationTwo.getPid());
                    if (ToolUtil.isNotEmpty(classificationThree)) {
                        productOrderDetailVO.setProductName(classificationThree.getName());
                    }
                }
            }

            //2.查询颜色
            Color color = colorService.getById(productOrder.getMaterial());
            if (ToolUtil.isNotEmpty(color)) {
                productOrderDetailVO.setMaterial(color.getName());
                Color colorTwo = colorService.getById(color.getPid());
                if (ToolUtil.isNotEmpty(colorTwo)) {
                    productOrderDetailVO.setColorNum(colorTwo.getName());
                    Color colorThree = colorService.getById(colorTwo.getPid());
                    productOrderDetailVO.setColor(colorThree.getName());
                }
            }

            //3.查询包装尺寸
            List<PackageSize> packageSizes = packageSizeService.getBaseMapper().selectList(new QueryWrapper<PackageSize>()
                    .lambda().eq(PackageSize::getProductOrderId, productOrder.getKindId()));
            if (ToolUtil.isNotEmpty(packageSizes)) {
                productOrderDetailVO.setPackageSizes(packageSizes);
            }

            //4.查询单位
            Unit unit = unitService.getById(productOrder.getUnit());
            if (ToolUtil.isNotEmpty(unit)) {
                productOrderDetailVO.setUnitName(unit.getUnitName());
            }
            Unit unitMin = unitService.getById(productOrder.getUnitMin());
            if (ToolUtil.isNotEmpty(unitMin)) {
                productOrderDetailVO.setUnitMin(unitMin.getUnitName());
            }
            Unit unitMax = unitService.getById(productOrder.getUnitMax());
            if (ToolUtil.isNotEmpty(unitMax)) {
                productOrderDetailVO.setUnitMax(unitMax.getUnitName());
            }

            //5.查询产品图片
            List<String> pics = Lists.newArrayList(SPLITTER.split(productOrder.getPicPath()));
            if (ToolUtil.isNotEmpty(pics)) {
                List<String> picNew = pics.stream().map(s -> SystemConstant.TENCENT_URL.concat(s)).collect(Collectors.toList());
                productOrderDetailVO.setPicPathList(picNew);
            }
            //6.查询报告
            List<String> reportCertificate = Lists.newArrayList(SPLITTER.split(productOrder.getReportCertificate()));
            if (ToolUtil.isNotEmpty(reportCertificate)) {
               List<String> New = reportCertificate.stream().map(s -> SystemConstant.TENCENT_URL.concat(s)).collect(Collectors.toList());
                productOrderDetailVO.setReportCertificate(New);
            }
            return ResponseData.success(200, "查询成功", productOrderDetailVO);
        }else {
            return ResponseData.error("掺入id为空！");
        }
    }


}



